package com.erp.module.xianChangPaiZhao

import androidx.appcompat.app.AlertDialog
import android.content.Intent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.AdapterView
import com.erp.CaptureActivity
import com.erp.Interface.OnUserDataInterface
import com.erp.R
import com.erp.bean.AnZhuangBean
import com.erp.module.crm.xXCrm.guiMingXi.GuimingxiActivity
import com.erp.myAdapter.AnZhuangAdapter
import com.erp.myFragment.BaseKFragment
import com.erp.permission.PermissionListener
import com.erp.util.JsonUtil
import com.erp.util.Myutil
import com.erp.util.PermissionUtils
import com.erp.view.PullToRefreshView
import kotlinx.android.synthetic.main.fragment_anzhuangzhinan.*
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject

/**
 * Created by Administrator on 2018/1/20/020.
 * 作者：刘洋
 */
class FragmentKXianchangPaizhao : BaseKFragment(), AdapterView.OnItemClickListener, View.OnClickListener, PullToRefreshView.OnFooterRefreshListener, PullToRefreshView.OnHeaderRefreshListener,XianChangPaiZhaoContract.XianChangPaiZhaoView {

    var type = 0
    private var sousuo = ""
    lateinit var updatedialog: AlertDialog
    lateinit var zhinanlist : MutableList<AnZhuangBean>
    lateinit var adapter : AnZhuangAdapter
    private val f = "FragmentKAnZhuang"
    lateinit var P : IXianChangPaiZhaoP
    override fun getLayoutId(): Int {
        fragmentname=f
        return R.layout.fragment_anzhuangzhinan
    }
    override fun initData() {
        zhinanlist=ArrayList()
        P = IXianChangPaiZhaoP(zhinanlist,context!!,this)
        adapter= AnZhuangAdapter(activity!!, zhinanlist)
        ZhiNanLv.adapter=adapter
        ZhiNanLv.onItemClickListener=this
        SouSuoIv.setOnClickListener(this)
        ScanIv.setOnClickListener(this)
        Pull.setheader(true)
        Pull.setOnFooterRefreshListener(this)
        Pull.setOnHeaderRefreshListener(this)
        LlScanTu.setOnClickListener(this)
        LlScanPhoto.setOnClickListener(this)
        if (isTiao) {
            isTiao = false
        }else{
            P.gainData("XianChangPaiZhao")
            Pull.headerRefreshing()
        }
        ZhiNanEt.setOnEditorActionListener { v, actionId, event ->
            var isOK = true
            when (actionId) {
                EditorInfo.IME_ACTION_SEARCH -> {
                    updatedialog = Myutil.showupdatedialog(activity, "正在搜索", false)
                    sousuo =  ZhiNanEt.text.toString()
                    P.sousuo(sousuo)
                }
                else -> isOK = false
            }
            isOK
        }
        if(sousuo != ""){
            update(sousuo)
        }
    }

    fun qingkong(){
        if(isFirstLoad){
            return
        }
        Pull.headerRefreshing()
    }

    override fun onClick(v: View?) {
        when(v){
            SouSuoIv -> {
                updatedialog = Myutil.showupdatedialog(activity, "正在搜索", false)
                sousuo =  ZhiNanEt.text.toString()
                P.sousuo(sousuo)
            }
            ScanIv -> {
                saoma()
            }
//            LlSaoMa -> {
//                saoma()
//            }
            LlScanTu -> {
                type = 2
                saoma()
            }
            LlScanPhoto -> {
                type = 1
                saoma()
            }
        }
    }

    fun saoma(){
        PermissionUtils.issaomiao(activity!!,object : PermissionListener {
            override fun onSucceed(requestCode: Int, grantPermissions: MutableList<String>) {
                val intent = Intent()
                intent.setClass(activity!!, CaptureActivity::class.java)
                intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
                startActivityForResult(intent, type)
            }

            override fun onFailed(requestCode: Int, deniedPermissions: MutableList<String>) {
                Myutil.MyTost("没有权限，无法扫描")
            }

        })
    }

    override fun onItemClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
        when(parent){
            ZhiNanLv -> {
                val intent = Intent(activity, XianchangPaizhaoActivity::class.java)
                intent.putExtra("code", 1)
                intent.putExtra("oid", zhinanlist[position].id)
                intent.putExtra("onum", zhinanlist[0].onum)
                startActivity(intent)
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(data==null){
            return
        }
        when (requestCode) {
            1 -> {
                val bundle = data.extras
                //显示扫描到的内容
                sousuo = bundle?.get("result") as String
                //显示扫描到的内容
                ZhiNanEt.setText(sousuo)
                updatedialog = Myutil.showupdatedialog(activity, "正在搜索", false)
                Myutil.MyTost(sousuo)
                P.sousuo(sousuo)
            }
            2 -> {
                val bundle = data.extras
                //显示扫描到的内容
                sousuo = bundle?.get("result") as String
                //显示扫描到的内容
                ZhiNanEt.setText(sousuo)
                updatedialog = Myutil.showupdatedialog(activity, "正在搜索", false)
                Myutil.MyTost(sousuo)
                getDingDan(sousuo)
            }

        }
    }
    var model = XianChangPaiZhapModel()
    fun getDingDan(sousuo : String){
//        var m = DingDanModel()
//        var b = OrderSousuoBean()
//        b.all = sousuo
        model.getanzhuangphoto(context!!, 0, 20, sousuo,object : OnUserDataInterface{
            override fun onUserData(data: String?) {
                if(data == null){
                    Myutil.MyTost("获取数据失败")
                    return
                }
                var list:  MutableList<AnZhuangBean> = ArrayList()
                try {
                    val js = JSONArray(data)
                    for (i in 0 until js.length()) {
                        val anzhuang = AnZhuangBean()
                        val jo = js.get(i) as JSONObject
                        anzhuang.customer_name= JsonUtil.getvolue(jo,"customer_name")
                        anzhuang.onum= JsonUtil.getvolue(jo,"onum")
                        anzhuang.shop_name= JsonUtil.getvolue(jo,"shop_name")
                        anzhuang.id= JsonUtil.getvolue(jo,"id")
                        list.add(anzhuang)
                    }
                } catch (e: JSONException) {
                    e.printStackTrace()
                }
                if(list.size > 0){
                    val intent = Intent(activity, GuimingxiActivity::class.java)
                    intent.putExtra("chaxun",true)
                    intent.putExtra("oid", list[0].id)
                    intent.putExtra("shengchan", list[0].onum)
                    startActivity(intent)
                }else{
                    Myutil.MyTost("没有找到单号")
                }
                updatedialog.dismiss()
            }

            override fun onNot(throwable: String?) {
                Myutil.MyTost("获取数据失败")
                updatedialog.dismiss()
            }

        })
    }


    fun setSousuo(s : String){
        type = 1
        this.sousuo = s;
    }

    fun update(s : String){
        //显示扫描到的内容
        ZhiNanEt.setText(s)
        updatedialog = Myutil.showupdatedialog(activity, "正在搜索", false)
        P.sousuo(s)
    }

    override fun xialaOk() {
        Pull.onHeaderRefreshComplete()
        adapter.notifyDataSetChanged()
        when(type){
            1 -> {
                if(zhinanlist.size != 0){
                    val intent = Intent(activity, XianchangPaizhaoActivity::class.java)
                    intent.putExtra("code", 2)
                    intent.putExtra("oid", zhinanlist[0].id)
                    intent.putExtra("onum", zhinanlist[0].onum)
                    startActivity(intent)
                    updatedialog.dismiss()
                    type = 0
                }else{
                    Myutil.MyTost("没有找到客户")
                    updatedialog.dismiss()
                }
            }
        }
        type = 0
    }

    override fun xialaNo() {
        Pull.onHeaderRefreshComplete()
        updatedialog.dismiss()
    }

    override fun shanglaOk() {
        Pull.onFooterRefreshComplete()
        adapter.notifyDataSetChanged()
    }

    override fun shanglaNo() {
        Pull.onFooterRefreshComplete()
    }
    override fun gainDataOk() {
        adapter.notifyDataSetChanged()
    }

    override fun onFooterRefresh(view: PullToRefreshView) {
        P.shangla()
    }
    override fun onHeaderRefresh(view: PullToRefreshView) {
        P.xiala()
    }
}